<template>
  <div class="edit-menu">
    <a-modal
      :title="propsData.type === 'add' ? '新增用户' : '修改用户'"
      width="900px"
      :visible="visibles"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="requestSpinning" tip="正在加载数据中...">
        <a-form :form="form">
          <a-row :gutter="10">
            <a-col :span="12">
              <a-form-item
                label="登录账号"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
              >
                <a-input
                  v-decorator="['LoginName',{
                    rules: [
                      { required: true, message: '', whitespace: true, trigger: 'change' },
                      { validator: validateLoginName }
                    ]
                  }]"
                  placeholder="请输入登录账号"
                  autocomplete="off"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col v-if="propsData.type !== 'update'" :span="12">
              <a-form-item label="登录密码" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input-password
                  v-decorator="[
                    'PassWord',{
                      rules: [
                        { required: true, message: '', whitespace: true, trigger: 'change' },
                        { validator: validatePassword }
                      ]
                    }
                  ]"
                  autocomplete="new-password"
                  placeholder="请输入登录密码" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="姓名" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input
                  v-decorator="[
                    'UserName',{
                      rules: [
                        { required: true, message: '', whitespace: true, trigger: 'change' },
                        { validator: validateUserName }
                      ]
                    }
                  ]"
                  autocomplete="off"
                  placeholder="请输入姓名" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="身份证号" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input
                  v-decorator="[
                    'IdCard',{
                      rules: [
                        { required: true, message: '', whitespace: true, trigger: 'change' },
                        { validator: validateIDCard }
                      ]
                    }
                  ]"
                  autocomplete="off"
                  placeholder="请输入身份证号" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="联系电话" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input
                  v-decorator="[
                    'Phone', {
                      rules: [
                        { required: false, message: '', whitespace: true, trigger: 'change' },
                        { validator: validatePhone }
                      ]
                    }
                  ]"
                  autocomplete="off"
                  placeholder="请输入联系电话" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="所属部门" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-tree-select
                  v-decorator="['DepID', { rules: [{ required: true, message: '请选择所属部门' }] }]"
                  :tree-data="departmentList"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :replaceFields="{
                    children:'children',
                    title:'DepartmentName',
                    key:'ID',
                    value: 'ID'
                  }"
                  treeNodeFilterProp="title"
                  allowClear
                  show-search
                  placeholder="请选择所属部门"
                  searchPlaceholder="输入部门名称进行筛选"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="拥有权限" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-select
                  v-decorator="['RoleID', { rules: [{ required: true, message: '请选择拥有权限' }] }]"
                  mode="multiple"
                  showArrow
                  allowClear
                  optionFilterProp="title"
                  :options="roleList"
                  :maxTagCount="2"
                  placeholder="请选择拥有权限"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="备注" :label-col="{ span: 2, offset: 1 }" :wrapper-col="{ span: 21 }">
            <a-textarea
              v-decorator="['Remark', { initialValue: '' }]"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入备注" />
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import md5 from 'md5'
import { getDepartmentSelect, getRoleSelect, getUserInfo, setUsers } from '@/api/system'
import { validPassword, validAccountNumber, validChineseChar, validIDCard, validTelphone } from '@/utils/validate'
export default {
  props: {
    visibles: {
      type: Boolean,
      default: false
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      confirmLoading: false,
      requestSpinning: false,
      isDevelopment: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      form: this.$form.createForm(this, { name: 'user' }),
      departmentList: [],
      roleList: [],
      jobData: []
    }
  },
  mounted () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      const { propsData: { id, type }, form: { setFieldsValue }, $message } = this
      this.requestSpinning = true
      const department = new Promise((resolve, reject) => {
        getDepartmentSelect({
          type: 'udepartment',
          Contype: this.$store.getters.loginName
        }).then(res => {
          resolve(res.data)
        })
      })
      const role = new Promise((resolve, reject) => {
        getRoleSelect({ userid: this.$store.getters.userid }).then(res => {
          resolve(res.data)
        })
      })
      const info = new Promise((resolve, reject) => {
        if (type === 'update') {
          getUserInfo({ userID: id }).then(res => {
            resolve(res)
          })
        } else {
          resolve({})
        }
      })
      Promise.all([department, role, info]).then(res => {
        this.departmentList = res[0]
        this.roleList = res[1].map(item => {
          item = {
            key: item.ROLENAME,
            title: item.ROLENAME,
            value: item.ID
          }
          return item
        })
        if (type === 'add') return
        const result = res[2].data
        this.$nextTick(() => {
          setFieldsValue({
            LoginName: result.LoginName,
            UserName: result.UserName,
            IdCard: result.IdCard,
            Phone: result.Phone,
            DepID: result.DepID,
            RoleID: result.RoleID === '' ? [] : result.RoleID.split(',').map(Number),
            Remark: result.Remark
          })
        })
      }).catch((err) => {
        $message.error(err)
      }).finally(() => {
        this.requestSpinning = false
      })
    },
    handleSubmit () {
      const { form: { validateFields }, propsData: { type, id } } = this
      validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          if (type === 'update') {
            values.UserID = id
          } else {
            values.PassWord = md5(values.PassWord)
          }
          setUsers({
            State: type,
            user: Object.assign({}, values, {
              RoleID: values.RoleID.join(),
              AddPeople: this.$store.getters.loginName,
              Mode: '0'
            })
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success(`${this.propsData.type === 'add' ? '添加' : '修改'}用户信息成功`, 3)
              this.handleCancel()
              this.$parent.$parent.$refs.table.refresh()
            } else {
              this.$message.error(res.msg, 3)
            }
          }).catch(() => {
            this.$message.error(`${this.propsData.type === 'add' ? '添加' : '修改'}用户信息失败`, 3)
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.$emit('update:visibles', false)
    },
    validateLoginName: (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入登录账号'))
      }
      if (!validAccountNumber(value)) {
        callback(new Error('请输入以字母开头的4-30位字母、数字或下划线的组合'))
      }
      callback()
    },
    validatePassword (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入登录密码'))
      }
      if (!validPassword(value)) {
        callback(new Error('请输入8-20位大写字母，小写字母，数字和特殊字符其中任意三种或三种以上组合'))
      }
      callback()
    },
    validateUserName (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入姓名'))
      }
      if (!validChineseChar(value)) {
        callback(new Error('姓名输入有误，请重新输入'))
      }
      callback()
    },
    validateIDCard (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入身份证号'))
      }
      if (!validIDCard(value)) {
        callback(new Error('身份证号输入有误，请重新输入'))
      }
      callback()
    },
    validatePhone (rule, value, callback) {
      if (!value) {
        callback()
      }
      if (!validTelphone(value)) {
        callback(new Error('联系电话输入有误，请重新输入'))
      }
      callback()
    }
  }
}
</script>
